package com.njcb.ams.support.security.service;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.njcb.ams.pojo.dto.standard.EntityResponse;
import com.njcb.ams.util.AmsJsonUtils;

@Component
public class LoginFailureAuthenticationHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String msg = "登录失败!";
		if (exception instanceof UsernameNotFoundException || exception instanceof AccountExpiredException) {
			msg = exception.getMessage();
		}  else if (exception instanceof BadCredentialsException) {
			msg = "密码输入错误!";
		} else if (exception instanceof DisabledException) {
			msg = "账户被禁用!";
		} else {
			msg = exception.getMessage();
		}
		out.write(AmsJsonUtils.objectToJson(EntityResponse.buildFail(msg)));
		out.flush();
		out.close();
	}

}
